package com.music.mysongs.helper

import android.content.Context
import android.content.Intent
import android.media.MediaPlayer
import android.net.Uri
import android.os.Build
import androidx.annotation.RequiresApi
import androidx.core.net.toUri
import com.google.gson.Gson
import com.music.mysongs.activity.MainActivity
import com.music.mysongs.bean.BeanManager
import com.music.mysongs.bean.SongBean
import com.music.mysongs.data.MusicCreatorData
import com.music.mysongs.file.*
import com.music.mysongs.utils.myGoActivity
import com.music.mysongs.utils.myLog
import com.music.mysongs.utils.myToastWithoutCxt
import java.io.IOException

@RequiresApi(Build.VERSION_CODES.M)
class PlayHelper(context: Context) {
    private val mTAG = "PlayerHelper"
    private var cxt = context
    private var player = MediaPlayer()
    private val beanManager = BeanManager()

    private var size: Int? = null
    private var sort: String? = null
    private var current: Int? = null
    private var song = SongBean(null, null, null, null, null)

    fun initPlay(kinds: String?, index: Int?) {
        myLog("$mTAG: initPlay kinds=$kinds index=$index")
        sort = kinds
        current = index
        index?.let {
            when (kinds) {
                null -> {
                    initSPF()
                }
                "web_pass" -> {
                    initWeb(it, "musicPass.json")
                }
                "web_audit" -> {
                    initWeb(it, "musicAudit.json")
                }
                "web_collect" -> {
                    initWeb(it, "musicColl.json")
                }
                "db_web_love" -> {
                    initDB(it, true)
                }
                "db_local" -> {
                    initDB(it, false)
                }
                else -> {
                    myLog("$mTAG:initPlay kinds=$kinds index=$index")
                }
            }
        }
        if (song.path != null) {
            myLog("$mTAG: sPath=${song.path}")
            initListen()
        } else {
            myLog("$mTAG: song=$song")
        }
    }

    private fun initSPF() {
        val lov = myCxtReadStringSPF(cxt, "spfSort")
        if (lov.isNullOrEmpty() || lov == "none") {
            myLog("第一次播放，从本地首曲开始听叭")
            sort = "db_local"
            current = 0
            initDB(0, false)
        } else {
            val pos = myCxtReadIntSPF(cxt, "spfPos")
            initPlay(lov, pos)
        }
    }

    private fun initDB(pos: Int, lov: Boolean) {
        size = beanManager.getBeanSize(lov)
        if (size == 0 || (lov && getNetWork() == null)) {
            myGoActivity(cxt, MainActivity::class.java)
        } else {
            song = beanManager.getBeanList(pos, lov)
        }
    }

    private fun initWeb(pos: Int, jFile: String) {
        val jsonFile = FileOP().read(cxt, jFile)
        val data = Gson().fromJson(jsonFile, MusicCreatorData.MusicData::class.java)
        myLog("$mTAG: data=$data")
        if (getNetWork() != null && data.code == 20000) {
            size = data.data!!.size
            song.webId = data.data[pos].id.toInt()
            song.title = data.data[pos].title
            song.artist = data.data[pos].artist
            song.path = turnPathUri(data.data[pos].audio)
            myLog("$mTAG: path=${data.data[pos].audio.toUri()}")
        } else {
            myGoActivity(cxt, MainActivity::class.java)
        }
    }

    private fun turnPathUri(path: String): Uri {
        return path.replaceFirst("//musicreator.com", "http://10.0.2.2").toUri()
    }

    private fun initListen() {
        myLog("$mTAG: initListen")
        try {
            player.reset()
            player.setDataSource(cxt, song.path!!)
            player.prepareAsync()
        } catch (e: IOException) {
            e.printStackTrace()
        }
        player.setOnPreparedListener {
            player.start()
            song.duration = player.duration.toLong()
            myCxtWriteSPF(cxt, "spfPos", null, current)
            myCxtWriteSPF(cxt, "spfSort", sort, null)
            myCxtWriteSPF(cxt, "spfTitle", song.title, null)
            myCxtWriteSPF(cxt, "spfArtist", song.artist, null)
            Intent().also { intentSongPrepared ->
                //intentSongPrepared.setPackage(cxt.packageName)
                intentSongPrepared.action = "com.music.mysongs.PREPARED"
                intentSongPrepared.putExtra("top_title", song.title)
                intentSongPrepared.putExtra("top_artist", song.artist)
                cxt.sendBroadcast(intentSongPrepared)
            }
        }
        player.setOnErrorListener { _, what, _ ->
            when (what) {
                MediaPlayer.MEDIA_ERROR_IO ->
                    myToastWithoutCxt("本地文件或网络相关错误-1004", 1)
                MediaPlayer.MEDIA_ERROR_TIMED_OUT ->
                    myToastWithoutCxt("播放超时错误-110", 1)
                MediaPlayer.MEDIA_ERROR_UNKNOWN ->
                    myToastWithoutCxt("未知错误0", 1)
                MediaPlayer.MEDIA_ERROR_SERVER_DIED ->
                    myToastWithoutCxt("媒体服务器挂机100", 1)//（应用必须释放对象，然后开启新的实例）
                MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK ->
                    myToastWithoutCxt("播放错误200", 1)//（一般视频播放比较慢或视频本身有问题会引发）
            }
            true
        }
        player.setOnBufferingUpdateListener { _, percent ->
            myLog("$mTAG:percent=$percent")
        }
        playOrder(getIsOrder())
    }

    fun getTitle(): String {
        return song.title!!
    }

    fun getArtist(): String {
        return song.artist!!
    }

    fun getCurrent(): Int {
        return player.currentPosition
    }

    fun getDuration(): Int {
        return player.duration
    }

    //是否播放
    fun getIsPlay(): Boolean {
        return player.isPlaying
    }

    fun playOrPause() {
        if (!player.isPlaying) {
            player.start()
        } else {
            player.pause()
        }
    }

    //是否喜欢
    fun getIsLove(): Boolean {
        return beanManager.getIsLove(song.path!!)//服务器path要设置成不一样的，不然都变爱心
    }

    fun setLove() {
        beanManager.setBeanLove(song)
    }

    //是否顺序
    fun getIsOrder(): Boolean {
        val mode = myCxtReadStringSPF(cxt, "spfMode")
        return if (mode.isNullOrEmpty() || mode == "none") {
            setOrder(true)
            playOrder(true)
            true
        } else {
            mode == "order"
        }
    }

    fun setPlayOrder() {
        val order = getIsOrder()
        setOrder(!order)
        playOrder(!order)
    }

    private fun setOrder(bo: Boolean) {
        val mode: String = if (bo) {
            "order"
        } else {
            "loop"
        }
        myCxtWriteSPF(cxt, "spfMode", mode, null)
    }

    private fun playOrder(bo: Boolean) {
        player.setOnCompletionListener {
            if (bo) {
                playNext()
            } else {
                initPlay(sort, current!!)
            }
            myLog("$mTAG:setOnCompletionListener")
        }
    }

    //拖进度
    fun playPull(po: Int) {
        player.seekTo(po)
    }

    fun playStop() {
        try {
            player.stop()
            player.seekTo(0)
            player.release()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    fun playLast() {
        if (current!! > 0) {
            current = current!! - 1
            initPlay(sort, current)
        }
    }

    fun playNext() {
        if (current!! == size!! - 1) {
            current = 0
        } else {
            current = current!! + 1
        }
        initPlay(sort, current!!)
    }
}